import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;

import java.io.*;
import java.net.*;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class NYA {
    public static Config getConfig() {
        Config config = new Config();
        if (!config.getConfig().containsKey("troops"))
            HT.Crash("配置文件错误 => 参数丢失 -> troops");
        if (!config.getConfig().containsKey("library"))
            HT.Crash("配置文件错误 => 参数丢失 -> library");
        if (!config.getConfig().containsKey("proxy"))
            HT.Crash("配置文件错误 => 参数丢失 -> proxy");
        return config;
    }

    public static Comic getComic(Config config, String id) throws IOException {
        switch (config.getString("library")) {
            case "online": {
                URL url = new URL("https://zh.yyhentai.com/g/" + id);
                Proxy proxy = config.getBoolean("proxy.source") ? new Proxy(Proxy.Type.HTTP, new InetSocketAddress(config.getString("proxy.host"), config.getInteger("proxy.port"))) : null;
                URLConnection connection = proxy == null ? url.openConnection() : url.openConnection(proxy);
                connection.setRequestProperty("accept", "*/*");
                connection.setRequestProperty("connection", "Keep-Alive");
                connection.setRequestProperty("user-agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/86.0.4240.111 Safari/537.36");
                Map<String, List<String>> map = connection.getHeaderFields();
                String resp = map.get(null).get(0);
                JSONObject jsonResponse = new JSONObject();
                jsonResponse.put("comicId", id);
                jsonResponse.put("comicResp", resp);
                if (resp.indexOf("200 OK") < 0)
                    return null;
                BufferedReader read = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
                String line;
                String result = "";
                while ((line = read.readLine()) != null)
                    result += line;
                {
                    String target = "";
                    {
                        Pattern pattern = Pattern.compile("<div id=\"cover\">.*?</noscript>\\s*?</a>\\s*?</div>");
                        Matcher matcher = pattern.matcher(result);
                        if (matcher.find()) {
                            String temp = matcher.group();
                            target = temp;
                        }
                    }
                    {
                        Pattern pattern = Pattern.compile("data-src=\".*?\"");
                        Matcher matcher = pattern.matcher(target);
                        if (matcher.find()) {
                            String temp = matcher.group();
                            temp = temp.substring(10, temp.lastIndexOf("\""));
                            temp = temp.substring(temp.indexOf("/galleries/") + 11, temp.indexOf("/cover"));
                            jsonResponse.put("comicGid", (Long.valueOf(temp)));
                        }
                    }
                    {
                        Pattern pattern = Pattern.compile("alt=\".*?\"");
                        Matcher matcher = pattern.matcher(target);
                        if (matcher.find()) {
                            String temp = matcher.group();
                            temp = temp.substring(5, temp.lastIndexOf("\""));
                            jsonResponse.put("comicTitle", temp);
                        }
                    }
                    {
                        Pattern pattern = Pattern.compile("<!-- <h1>.*?</h1> -->");
                        Matcher matcher = pattern.matcher(result);
                        if (matcher.find()) {
                            String temp = matcher.group();
                            temp = temp.substring(9, temp.lastIndexOf("</h1>"));
                            jsonResponse.put("comicAlias", temp);
                            if (jsonResponse.get("comicTitle") == null || jsonResponse.getString("comicTitle").length() == 0) {
                                jsonResponse.put("comicTitle", temp);
                            }
                        }
                    }
                }
                {
                    Pattern pattern = Pattern.compile("<section id=\"tags\">.*?</section>");
                    Matcher matcher = pattern.matcher(result);
                    if (matcher.find()) {
                        String temp = matcher.group();
                        temp = temp.replaceAll("</?span.*?>", " ").replaceAll("</?a.*?>", " ");
                        temp = temp.replaceAll("</?section.*?>", "").replaceAll("</?div.*?>", "\n");
                        temp = temp.replaceAll("\t", "").replaceAll("\n\n", "\n");
                        while (temp.startsWith("\n")) {
                            temp = temp.substring(1);
                        }
                        while (temp.endsWith("\n")) {
                            temp = temp.substring(0, temp.length() - 1);
                        }
                        while (temp.contains("  ")) {
                            temp = temp.replaceAll("  ", " ");
                        }
                        jsonResponse.put("comicTag", temp);
                    }
                }
                {
                    Integer count = 0;
                    Pattern pattern = Pattern.compile("gallerythumb");
                    Matcher matcher = pattern.matcher(result);
                    while (matcher.find()) {
                        count++;
                    }
                    jsonResponse.put("comicPage", Long.valueOf(count));
                }
                return new Comic(jsonResponse);
            }
            case "self": {
                URL url = new URL("http://rds-api.delamer.ltd:80/api/comic/selectComicById?comicId=" + id);
                Proxy proxy = config.getBoolean("proxy.source") ? new Proxy(Proxy.Type.HTTP, new InetSocketAddress(config.getString("proxy.host"), config.getInteger("proxy.port"))) : null;
                URLConnection connection = proxy == null ? url.openConnection() : url.openConnection(proxy);
                Map<String, List<String>> map = connection.getHeaderFields();
                BufferedReader read = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
                String line;
                String response = "";
                while ((line = read.readLine()) != null)
                    response += line;
                JSONObject jsonResponse = JSON.parseObject(response);
                if (!jsonResponse.getString("code").equals("200")) {
                    return null;
                }
                JSONObject jsonObject = JSON.parseObject(jsonResponse.getString("data"));
                if (!jsonObject.getString("comicResp").equals("HTTP/1.1 200 OK")) {
                    return null;
                }
                return new Comic(jsonObject);
            }
            case "test": {
                URL url = new URL("http://127.0.0.1:8099/api/comic/selectComicById?online=false&comicId=" + id);
                Proxy proxy = config.getBoolean("proxy.source") ? new Proxy(Proxy.Type.HTTP, new InetSocketAddress(config.getString("proxy.host"), config.getInteger("proxy.port"))) : null;
                URLConnection connection = proxy == null ? url.openConnection() : url.openConnection(proxy);
                Map<String, List<String>> map = connection.getHeaderFields();
                BufferedReader read = new BufferedReader(new InputStreamReader(connection.getInputStream(), "UTF-8"));
                String line;
                String response = "";
                while ((line = read.readLine()) != null)
                    response += line;
                JSONObject jsonResponse = JSON.parseObject(response);
                if (!jsonResponse.getString("code").equals("200")) {
                    return null;
                }
                JSONObject jsonObject = JSON.parseObject(jsonResponse.getString("data"));
                if (!jsonObject.getString("comicResp").equals("HTTP/1.1 200 OK")) {
                    return null;
                }
                return new Comic(jsonObject);
            }
            default:
                HT.Crash("配置文件错误 - 'library'参数异常");
                return null;
        }
    }


    public static void setInfoFile(Comic comic) throws IOException {
        File info = HT.File(System.getProperty("user.dir") + "\\" + comic.getComicId() + "\\info.txt");
        FileWriter fw = new FileWriter(info);
        fw.write(comic.toString());
        fw.flush();
        fw.close();
    }

    public static void doDownload(Config config, Comic comic) {
        ThreadPoolExecutor executor = (ThreadPoolExecutor) Executors.newFixedThreadPool(config.getInteger("troops"));
        Proxy proxy = config.getBoolean("proxy.image") ? new java.net.Proxy(java.net.Proxy.Type.HTTP, new InetSocketAddress(config.getString("proxy.host"), config.getInteger("proxy.port"))) : null;
        Integer page = comic.getComicPage();
        for (int i = 0; i <= page; i++) {
            if (i == 0) {
                String link = "https://t2.orzcdn.xyz/galleries/%gid%/cover".replace("%gid%", comic.getComicGid().toString());
                String path = System.getProperty("user.dir") + "\\" + comic.getComicId() + "\\";
                Quest quest = new Quest(proxy, link, path);
                executor.execute(quest);
            } else {
                String link = "https://i1.tspcdn.xyz/galleries/%gid%/".replace("%gid%", comic.getComicGid().toString()) + i;
                String path = System.getProperty("user.dir") + "\\" + comic.getComicId() + "\\file\\";
                Quest quest = new Quest(proxy, link, path);
                executor.execute(quest);
            }

            //执行中 executor.getPoolSize()
            //等待中 executor.getQueue().size()
            //已执行 executor.getCompletedTaskCount()
            // System.out.println("执行中:" + executor.getPoolSize() + "，等待中" + executor.getQueue().size() + "，已执行" + executor.getCompletedTaskCount());
        }
        executor.shutdown();
        while (executor.getCompletedTaskCount() <= page) {
            HT.Log("下载中:" + executor.getPoolSize() + "，等待中" + executor.getQueue().size() + "，已下载" + executor.getCompletedTaskCount());
            try {
                TimeUnit.SECONDS.sleep(1);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        HT.Log("下载中:" + executor.getPoolSize() + "，等待中" + executor.getQueue().size() + "，已下载" + executor.getCompletedTaskCount());
        HT.Log("下载完毕!");
    }

    public static void doPackage(Comic comic) throws IOException {
        String title = comic.getComicTitle();
        title = title
                .replace(":", "：")
                .replace("?", "？")
                .replace("\\", "＼")
                .replace("/", "／")
                .replace("*", "＊")
                .replace("\"", "〃")
                .replace("<", "〈")
                .replace(">", "〉")
                .replace("|", "｜");
        String source = System.getProperty("user.dir") + "\\" + comic.getComicId() + "\\file\\";
        String target = System.getProperty("user.dir") + "\\" + comic.getComicId() + "\\";
        String fileName = title + ".zip";
        HT.Log("==>> Package " + title);
        HT.Package(source, target, fileName);
    }
}
